package com.zhiwei.version.git.entity;

import lombok.Data;
import org.eclipse.jgit.lib.Ref;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.*;

/**
 * function git分支实体
 * author zhiwei.yang
 * time 2020-3-4-16:39
 */
@Data
public class GitBranchInfo {

    /** 本地分支列表 **/
    private Set<String> localBranchList = new HashSet<>();
    private Map<String, Ref> localBranchRefMap = new HashMap<>();

    /**
     * 远程分支列表
     */
    private Set<String> remoteBranchList = new HashSet<>();
    private Map<String, Ref> remoteBranchRefMap = new HashMap<>();

    /**
     * 获取所有
     * @return
     */
    public List<String> getAllBranchList(){
        List<String> allBranchList = new ArrayList<>(localBranchList);
        allBranchList.addAll(remoteBranchList);
        return allBranchList;
    }

    /**
     * 判断本地分支是否存在
     * @param branch 分支名
     * @return
     */
    public boolean isExistLocalBranch(String branch){
        return isContainByList(localBranchList, branch);
    }

    /**
     * 判断远程分支是否存在
     * @param branch 分支名
     * @return
     */
    public boolean isExistRemoteBranch(String branch){
        return isContainByList(remoteBranchList, branch);
    }

    /**
     * 判断分支是否存在
     * @param branch 分支名
     * @return
     */
    public boolean isExistBranch(String branch){
        return isContainByList(getAllBranchList(), branch);
    }

    /**
     * 获取本地分支Ref
     * @param branch
     * @return
     */
    public Ref getLocalBranchRef(String branch){
        if(isExistLocalBranch(branch)){
            return localBranchRefMap.get(branch);
        }
        return null;
    }

    /**
     * 判断集合元素是否部分包含指定字符串
     * @param item 待比较字符串
     * @param collection 数据集合
     * @return
     */
    private boolean isContainByList(Collection<String> collection,String item){
        if(CollectionUtils.isEmpty(collection) || StringUtils.isEmpty(item)){
            return false;
        }
        return collection.stream().filter(tempStr -> tempStr.contains(item)).count() >= 1;
    }
}
